<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/21
 * Time: 14:08
 * Auth: YWH
 */

namespace App\Models;


use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MachineModel extends Model
{
    const CMD_OPEN_DOOR = 'OpenDoor';
    const CMD_W_UID = 'WriteUid';
    const CMD_D_UID = 'DeleteUid';
    const CMD_C_UID = 'ClearUid';
    const CMD_RESTART = 'Restart';



    public $error = '';

    public $table = "machine";
    public $primaryKey = 'machine_id';
    const CREATED_AT = 'create_time'; //修改created_at默认的字段名

    protected $fillable = ['hotel_id','machine_name','room_num','mac','updated_at','created_at'];

    public static function getMachineList($page=null)
    {
        $data = self::query()
        ->select(['hotel.name as hotel_name','hotel.address as hotel_address','machine.*'])
        ->orderBy("machine_id",'desc')
        ->join('hotel','machine.hotel_id','=','hotel.hotel_id','left')
        ->paginate(5,['*'], 'page', $page);
        return  $data;
    }


    public static function searchMachineList($postData,$page=null,$is_page=true)
    {
        $data = self::query()
            ->select(['hotel.name as hotel_name','hotel.address as hotel_address','machine.*'])
            ->orderBy("machine_id",'desc')
            ->join('hotel','machine.hotel_id','=','hotel.hotel_id','left');


        foreach($postData as $key => $val){
            $op = '=';
            if(in_array($key,['machine.mac','machine.machine_id','machine.machine_name','machine.room_num'])){
                $op = 'like';
                $val = '%'.$val.'%';
            }
            if($key == 'machine.hotel_id' && $val == 0){
                continue;
            }
            $data = $data -> where($key,$op,$val);
        }
        if($is_page){
            $data           = $data  ->paginate(5,['*'], 'page', $page);
        }else{
            $data = $data -> get() -> toArray();
        }
        return  $data;
    }

    public function send_command($command,$data,$method = 'GET')
    {
        $http_client = new Client([
            'base_uri' => config('url.SOCKET_URL'),
        ]);
        $response = $http_client -> request($method,'/Order/MachineController/'.$command,$data);
        $body = $response -> getBody();
        $res = json_decode($body -> getContents(),true);
        if(empty($res)){
            $this -> error = 'response获取失败';
            return false;
        }
        if($res['ret'] == 400){
            $this -> error = $res['msg'];
            return false;
        }
        return true;

    }

    public function open_door($mac = '0A0B0C123456')
    {
        return $this -> send_command(self::CMD_OPEN_DOOR,[
            'query' => ['mac' => $mac]
        ]);
    }

    public function write_uid($mac,$uid)
    {
        return $this -> send_command(self::CMD_W_UID,[
            'query' => [
                'mac' => $mac,
                'uid' => $uid
            ]
        ]);
    }

    public function delete_uid($mac,$uid)
    {
        return $this -> send_command(self::CMD_D_UID,[
            'query' => [
                'mac' => $mac,
                'uid' => $uid
            ]
        ]);
    }

    public function clear_uid($mac)
    {
        return $this -> send_command(self::CMD_C_UID,[
            'query' => [
                'mac' => $mac,
            ]
        ]);
    }

    public function restart($mac)
    {
        return $this -> send_command(self::CMD_RESTART,[
            'query' => [
                'mac' => $mac,
            ]
        ]);
    }

    /**设备的添加或编辑
     * @param $postdata
     * @return \Illuminate\Database\Eloquent\Builder|Model|int
     */
    public static function save_machine($postdata)
    {
        if(empty($postdata['machine_id'])){
            return (new static)->add_machine($postdata);
        }
        return (new static)->edit_machine($postdata);
    }

    public function add_machine($postdata)
    {
        DB::beginTransaction();
        try{
            $model = self::query()
                -> create($postdata);
            if($model){
                $res = MachineGoodsModel::apply_template(null,$model->machine_id);
                if(!$res){
                    throw new \Exception('新建设备时应用模板失败!'.MachineGoodsModel::$error);
                }
            }else{
                throw new \Exception('添加设备失败!');
            }
            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            $this -> error = $exception -> getMessage();
            return false;
        }

    }

    public function edit_machine($postdata)
    {
        return self::query()
            -> where('machine_id','=',$postdata['machine_id'])
            -> update($postdata);
    }

    /**
     * 解除设备与mac的绑定
     * 删除该设备
     */
    public static function unbind_machine($postdata)
    {
        if(empty($postdata['machine_id'])){
            return true;
        }

        #order表不变
        #machine_goods表不变 该设备id不再查询
        #machine表的mac释放
        $machine_model = self::query()
            -> find($postdata['machine_id']);
        if(!$machine_model){
//            $machine_model -> mac = '';
//            $machine_model -> disabled = 1;
            return true;
        }
//        $machine_model -> save();
        $machine_model -> delete();
        return true;
    }

    /**根据mac地址获取设备信息
     * @param $mac
     * @return array|bool
     */
    public static function apiGetMachineByMac($mac)
    {
        $model = self::query()
            ->where('mac','=',$mac)
            ->first();
        return empty($model) ? false : $model->toArray();
    }
}